package thinker.miracle.commons;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * @author bo.chen
 *
 * @param <T>
 */
public class Page<T> implements Serializable{
	
	private static final long serialVersionUID = 1L;

	// 页码，默认是第一页
	private int pageNo = 1;
	
	// 每页显示的记录数，默认是20
	private int pageSize = 20;	
	
	// 总记录数
	private int totalRecord;	
	
	// 总页数
	private int totalPage;		
	
	// 对应的当前页记录
	private List<T> results;
	
	// 其他的参数我们把它分装成一个Map对象
	private Map<String, Object> params = new HashMap<String, Object>();

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalRecord() {
		return totalRecord;
	}

	public void setTotalRecord(int totalRecord) {
		this.totalRecord = totalRecord;
		int totalPage = totalRecord % pageSize == 0 ? totalRecord / pageSize
				: totalRecord / pageSize + 1;
		this.setTotalPage(totalPage);
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public List<T> getResults() {
		return results;
	}

	public void setResults(List<T> results) {
		this.results = results;
	}

	public Map<String, Object> getParams() {
		return params;
	}

	public void setParams(Map<String, Object> params) {
		this.params = params;
	}
	
	public void putParam(String key,Object value){
		this.params.put(key, value);
	}
	
	public void removeParam(String key){
		this.params.remove(key);
	}
	
	public void setRequest(HttpServletRequest request){
		this.pageNo = Integer.parseInt( request.getParameter("pageNo") == null ? "1" : request.getParameter("pageNo"));
		this.pageSize = request.getParameter("pageSize") == null ? this.pageSize:Integer.parseInt(request.getParameter("pageSize"));
	}
	
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Page [pageNo=").append(pageNo).append(", pageSize=")
				.append(pageSize).append(", results=").append(results)
				.append(", totalPage=").append(totalPage)
				.append(", totalRecord=").append(totalRecord).append("]");
		return builder.toString();
	}

}